<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10 paddingBottom20">
        <div class="mainor_form">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="40px"
            id="form"
          >
            <div class="main_tile box">
              <div class="main_tile_l"><em></em>分工方式</div>
            </div>
            <el-form-item>
              <div class="flex">
                <div
                  style="margin-right:30px"
                  v-for="(items, index) in firstArr"
                  :key="index"
                >
                  <el-radio
                    v-model="form.first_type"
                    @change="changes(items, 1)"
                    :label="items.id"
                    >{{ items.name }}
                  </el-radio>
                </div>
              </div>

              <div class="flex" style="margin-left:30px">
                <div
                  v-for="(its, lin) in secondArr"
                  :key="lin"
                  style="margin-right:20px"
                >
                  <el-radio
                    v-model="form.second_type"
                    @change="changes($event, 2)"
                    :label="lin"
                    >{{ its }}
                  </el-radio>
                </div>
              </div>
            </el-form-item>

            <div class="clearfix"></div>

            <el-form-item class="marginTop10">
              <el-button
                class="reset marginLeft10"
                type="primary"
                @click="getArticleList(1)"
                >重置</el-button
              >
              <el-button
                type="primary"
                @click="getArticleList(2)"
                :loading="listLoading"
                >保存</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="main_tile box marginTop20">
          <div class="main_tile_l"><em></em>分拣小组</div>
        </div>
        <div class="flex">
          <div class="txt-color">
            1.按商品或用户多维度设置分拣小组，完成分拣员任务的分工；2.设置好分拣小组后，只对触摸屏分拣端、小程序分拣端有效 
          </div>

          <el-button type="primary" @click="addGroup((type = 1))"
            >新增</el-button
          >
        </div>

        <div class="main_table marginTop10" style="min-height: 400px">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
          >
            <el-table-column label="小组名称" prop="name" />

            <el-table-column label="分拣员" prop="">
              <template slot-scope="scope">
                <el-tag
                  v-for="item in scope.row.sort_ids"
                  :key="item"
                  type="success"
                  style="margin: 2px 3px"
                  >{{ sortuser[item] }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="分拣科目" prop="">
              <template slot-scope="scope">
                <el-tag
                  v-for="item in scope.row.sort_subject"
                  :key="item"
                  type="success"
                  style="margin: 2px 3px"
                  >{{ sortsubject[item] }}</el-tag
                >
              </template>
            </el-table-column>

            <el-table-column
              label="管理操作"
              align="left"
              fixed="right"
              width="180"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <el-link
                  type="primary"
                  @click="editGroup(scope.row, (type = 2))"
                  >编辑</el-link
                >
                <el-link type="danger" @click="delGroup(scope.row)"
                  >删除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="main_page boxdq">
          <div></div>
          <div class="main_page_r">
            <el-pagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>

        <el-dialog
          :title="type == 1 ? '新增小组' : '编辑小组'"
          :visible.sync="addedFormVisible"
          width="26%"
          @close="close(1)"
        >
          <el-form
            :model="userForm"
            :rules="rules"
            ref="userForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="小组名称：" prop="name">
              <el-input
                class="wid240"
                placeholder="请输入小组名称"
                v-model="userForm.name"
              ></el-input>
            </el-form-item>

            <div class="check_box">
              <div class="check">
                <div class="sort_flex">
                  <div style="flex:1">分拣员</div>
                  <div>{{ checkfirst.length }}/{{ userlen }}</div>
                </div>
                <el-checkbox-group v-model="checkfirst">
                  <div class="flex_box">
                    <el-checkbox
                      v-for="(sit, sindex) in user_list"
                      :key="sindex"
                      :label="sindex"
                      >{{ sit }}</el-checkbox
                    >
                  </div>
                </el-checkbox-group>
              </div>

              <div class="check" style="margin-left:15px">
                <div class="sort_flex">
                  <div style="flex:1">分拣科目</div>
                  <div>{{ checksecond.length }}/{{ subjectlen }}</div>
                </div>
                <el-checkbox-group v-model="checksecond">
                  <div class="flex_box">
                    <el-checkbox
                      v-for="(item, lindex) in subject_list"
                      :key="lindex"
                      :label="lindex"
                      >{{ item }}</el-checkbox
                    >
                  </div>
                </el-checkbox-group>
              </div>
            </div>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="close(2)">取 消</el-button>
            <el-button type="primary" @click="setupmine">保 存</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {
  sortwork_index,
  sortwork_save,
  sortwork_base,
  sortgroup_add,
  sortgroup_edit,
  sortgroup_del
} from "@/api/sorting/sortingManagement";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";

export default {
  components: {},
  data() {
    return {
      current: {
        page: 1,
        per_page: 20
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      list: [],
      listLoading: false,
      // 保存数据
      form: {
        first_type: "", //商品
        second_type: "" //用户
      },
      sortsubject: [], //分拣科目
      sortuser: [], //分拣员
      firstArr: [], //一级勾选
      secondArr: [], //二级勾选
      work_type: "",
      type: 1,
      addedFormVisible: false,
      subject_list: {},
      user_list: {},
      userForm: {
        name: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入分工小组名称", trigger: "blur" }
        ]
      },
      checkfirst: [], //分拣员选择
      checksecond: [], //分拣科目选择
      userlen: "",
      subjectlen: "",
      id: "" //编辑时候传的id
    };
  },
  created() {
    // 列表
    this.sortwork_index();
  },
  methods: {
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.sortwork_index();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.sortwork_index();
    },
    changePage(page) {
      this.current.page = page;
      this.sortwork_index();
    },
    // 列表
    sortwork_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.current)) +
              apiUrl().appsecret
          )
        },
        apiUrl().name,
        this.current
      );
      sortwork_index(data).then(res => {
        this.listLoading = false;
        if (res.errcode == 0) {
          res.data.list.data.map(e => {
            e.sort_ids = e.sort_ids.split(",");
            e.sort_subject = e.sort_subject.split(",");
          });
          let arr = {};
          if (res.data.work_type != null) {
            res.data.arr.map(c => {
              if (res.data.work_type.first_type == c.id) {
                this.form.first_type = c.id;
                arr = c.self;
              }
            });
          } else {
            this.form.first_type = res.data.arr[0].id;
            this.secondArr = res.data.arr[0].self;
            this.form.second_type = Object.keys(this.secondArr)[0];
          }

          if (res.data.work_type) {
            let id = res.data.work_type.second_type;
            this.secondArr = arr;

            for (let i in arr) {
              if (id == i) {
                this.form.second_type = i;
              }
            }
          }
          this.work_type = res.data.work_type;
          this.list = res.data.list.data;
          this.sortsubject = res.data.subject;
          this.sortuser = res.data.sort_user;
          this.firstArr = res.data.arr;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    //编辑小组
    editGroup(row) {
      this.id = row.id;
      let arr = {
        id: this.id
      };
      this.sortwork_base(arr);
      this.addedFormVisible = true;
      this.checkfirst = row.sort_ids;
      this.checksecond = row.sort_subject;
      this.userForm.name = row.name;
    },
    //删除小组
    delGroup(row) {
      this.$confirm(`确认删除【${row.name}】分拣小组吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              )
            },
            apiUrl().name,
            { id: row.id }
          );
          sortgroup_del(data).then(res => {
            if (res.errcode == 0) {
              this.$message.success("删除成功");
              this.sortwork_index();
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    //添加小组
    addGroup() {
      if (this.form.first_type != "" && this.form.second_type != "") {
        if (this.work_type != null) {
          this.addedFormVisible = true;
          let arr = {
            id: ""
          };
          this.sortwork_base(arr);
        } else {
          this.$message.error("请先保存分工方式，在新增分工小组");
        }
      } else {
        this.$message.error("请先选择分工方式");
      }
    },
    // 新增保存
    add() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                name: this.userForm.name,
                sort_ids: this.checkfirst,
                sort_subject: this.checksecond
              })
            ) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        {
          name: this.userForm.name,
          sort_ids: this.checkfirst,
          sort_subject: this.checksecond
        }
      );
      sortgroup_add(data).then(res => {
        this.addedFormVisible = false;
        if (res.errcode == 0) {
          this.$message({
            message: "新增成功",
            type: "success"
          });
          this.sortwork_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 编辑保存
    edit() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                name: this.userForm.name,
                sort_ids: this.checkfirst,
                sort_subject: this.checksecond
              })
            ) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        {
          id: this.id,
          name: this.userForm.name,
          sort_ids: this.checkfirst,
          sort_subject: this.checksecond
        }
      );
      sortgroup_edit(data).then(res => {
        this.addedFormVisible = false;
        if (res.errcode == 0) {
          this.$message({
            message: "编辑成功",
            type: "success"
          });
          this.sortwork_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    //保存和重置方法
    getArticleList(type) {
      let arr = {};
      if (type == 1 && this.work_type == null) {
        this.$confirm(`重置后所有分拣小组将删除，确认删除？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.$message.success("重置成功");
            this.sortwork_index();
            this.form.first_type = "";
            this.form.second_type = "";
          })
          .catch(() => {});
      }
      if (type == 1 && this.work_type != null) {
        this.$confirm(`重置后所有分拣小组将删除，确认删除？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            let list = {
              type: 1,
              first_type: this.form.first_type,
              second_type: this.form.second_type
            };
            arr = list;
            this.sortwork_save(arr);
            this.form.first_type = "";
            this.form.second_type = "";
          })
          .catch(() => {});
      }
      if (type == 2 && this.work_type != null) {
        this.$confirm(`保存后所有分拣小组将删除，确认删除？`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            let list = {
              first_type: this.form.first_type,
              second_type: this.form.second_type
            };
            arr = list;
            this.sortwork_save(arr);
          })
          .catch(() => {});
      }
      if (type == 2 && this.work_type == null) {
        let list = {
          first_type: this.form.first_type,
          second_type: this.form.second_type
        };
        arr = list;
        this.sortwork_save(arr);
      }
    },
    //保存接口
    sortwork_save(arr) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        arr
      );
      sortwork_save(data).then(res => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.$message.success(res.errmsg);
          this.sortwork_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    //一级单选事件
    changes(items, type) {
      if (type == 1) {
        this.form.first_type = items.id;
        this.secondArr = items.self;
        this.form.second_type = Object.keys(this.secondArr)[0];
      } else {
        this.form.second_type = items;
      }
    },

    // 确认提交
    setupmine() {
      this.$refs["userForm"].validate(valid => {
        if (valid) {
          this.type == 2 ? this.edit() : this.add();
        }
      });
    },
    //分拣科目和分拣员接口
    sortwork_base(arr) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          )
        },
        apiUrl().name,
        arr
      );
      sortwork_base(data).then(res => {
        if (res.errcode == 0) {
          this.subject_list = res.data.sort_subject;
          this.user_list = res.data.sort_user;
          this.userlen = Object.keys(this.user_list).length;
          this.subjectlen = Object.keys(this.subject_list).length;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    //关闭事件
    close(type) {
      if (type == 1) {
        this.checksecond = [];
        this.checkfirst = [];
        this.addedFormVisible = false;
        this.userForm.name = "";
      } else {
        this.checksecond = [];
        this.checkfirst = [];
        this.addedFormVisible = false;
        this.userForm.name = "";
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 180px);
  }
}
/deep/ .main_table .el-table--small td .cell {
  height: auto;
  white-space: normal !important;
  p {
    margin: 0 5px;
    background-color: #f0f9eb;
    color: #67c23a;
    padding: 2px 0;
  }
}
.txt-color {
  flex: 1;
  color: #e47c02;
  font-size: 14px;
  padding-top: 8px;
}
.main_tile .main_tile_l {
  margin-left: 0px;
}

/deep/.el-radio__inner {
  border: 1px solid #ccc;
}
/deep/.el-radio__inner::after {
  left: 7px;
  top: 7px;
}

.flex {
  display: flex;
}
/deep/.el-dialog__title {
  font-size: 14px;
}
/deep/.el-dialog__header {
  border-bottom: 1px solid #f2f2f2;
  padding: 10px 15px;
}
.check_box {
  display: flex;
  width: 90%;
  margin: 0 auto;
  padding-top: 10px;
}
.check {
  width: 50%;
  border: 1px solid #f2f2f2;
  height: 300px;
}
.sort_flex {
  display: flex;
  background-color: #f5f7fa;
  border-bottom: 1px solid #f2f2f2;
  padding: 10px;
  font-size: 15px;
}
.flex_box {
  display: flex;
  flex-direction: column;
  height: 250px;
  overflow-x: auto;
  box-sizing: border-box;
}
/deep/.el-checkbox-group {
  padding: 6px 0px 0px 10px;
}
/deep/.el-checkbox {
  height: 25px;
  line-height: 25px;
  margin-right: 0px;
}
/deep/.el-dialog__footer {
  padding: 15px 20px;
  border-top: 1px solid #f2f2f2;
}
</style>
